<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

// 公共函数
$CI =&get_instance();

//提示成功信息
function comment_success($msg, $jumpurl="", $showmsg=false) {
	echo show_message($msg, $jumpurl, 2, false, $showmsg, "commentpost");
	exit;
}

//提示成功信息
function show_success($msg, $jumpurl="", $showmsg=false) {
	echo show_message($msg, $jumpurl, 2, false, $showmsg);
	exit;
}

//提示失败信息
function show_failed($msg, $jumpurl="") {
	echo show_message($msg, $jumpurl, 1);
	exit;
}

//后台提示成功信息
function admin_show_success($msg, $jumpurl="", $showmsg=false) {
	echo show_message($msg, $jumpurl, 2, 1, $showmsg);
	exit;
}

//后台提示失败信息
function admin_show_failed($msg, $jumpurl="") {
	echo show_message($msg, $jumpurl, 1, 1);
	exit;
}

//输出提示信息
//msgtype = 1 error
//msgtype = 2 success
function show_message($msg, $jumpurl="", $msgtype=1, $admin = false, $showmsg = true, $pos = "") {
	global $CI;
	if(is_null($CI)) $CI =&get_instance();
	
	//连接处理
//	(isset($_SERVER['HTTP_REFERER'])) ? $preurl = $_SERVER['HTTP_REFERER'] : $preurl = "javascript:history.go(-1)";
	(isset($_SERVER['HTTP_REFERER'])) ? $preurl = $_SERVER['HTTP_REFERER'] : $preurl = gurl('/');
	($jumpurl == "") ? $jumpurl = $preurl : $jumpurl = gurl($jumpurl);
	
	//锚点
	if($pos != "") {
		$jumpurl .= "#".$pos;
	} 
	
	if (!$showmsg) {//不提示信息
		redirect($jumpurl);
		return ;
	}
	
	ob_start();
	//输出header
	if(!$admin) $CI->autoload_model->output_header();

	//输出view处理
	($msgtype == 1) ? $view = "show_failed" : $view = "show_success";

	$viewdata = array("msg"=>$msg, "jumpurl"=>$jumpurl);
	header("Content-Type:text/html;charset=utf-8");
	$CI->load->view("common/".$view, $viewdata);

	
	//输出footer
	if(!$admin) $CI->autoload_model->output_footer();
	$buffer = ob_get_contents();
	ob_end_clean();
	return $buffer;
}

//js格式化输出
function jsoutputformat ($str)
{
    $str = trim ($str);
    $str = str_replace ('\\s\\s', '\\s', $str);
    $str = str_replace (chr(10), '', $str);
    $str = str_replace (chr(13), '', $str);
    $str = str_replace ('   ', '', $str);
    $str = str_replace ('\\', '\\\\', $str);
    $str = str_replace ('"', '\\"', $str);
    $str = str_replace ('\\\'', '\\\\\'', $str);
    $str = str_replace ("'", "\'", $str);
    return $str;
}

//获取内容图片
function get_content_pics($content)
{
	preg_match_all ("/<(img|IMG)(.*)(src|SRC)=[\"|'|]{0,}([h|\/].*(jpg|jpeg|JPEG|JPG|gif|GIF|png|PNG))[\"|'|\s]{0,}/isU",$content,$out);
	return $out[4];
}

//分页处理
function pages($base_url, $total_rows, $uri_segment = 3, $per_page = 20, $querystring = false)
{
	global $CI;
	if(is_null($CI)) $CI =&get_instance();
	//分页数据处理
	$CI->load->library('pagination');
	$config['base_url'] = $base_url;
	$config['total_rows'] = $total_rows;
	$config['per_page'] = $per_page;
	$config['uri_segment'] = $uri_segment;
	$config['num_links'] = 5;
	$config['first_link'] = '第一页';
	$config['last_link'] = '最末页';
	$config['prev_link'] = '上页';
	$config['next_link'] = '下页';
	$config['cur_tag_open'] = '<a class="sel">';
	$config['cur_tag_close'] = '</a>';
	if ($querystring) {
		$config['query_string_segment'] = "page";
		$config['page_query_string'] = TRUE;
	}
	
	$CI->pagination->initialize($config);
	$pagestring = $CI->pagination->create_links();
	return $pagestring;
}

//字符截取
function msubstr($fStr, $fStart, $fLen, $fCode = "utf-8",$show = '...') 
{
      if(function_exists('mb_substr')) {
          if(mb_strlen($fStr, $fCode) > $fLen) {
              return mb_substr ($fStr, $fStart, $fLen, $fCode) . $show;
          }
          return mb_substr ($fStr, $fStart, $fLen, $fCode);
      }else if(function_exists('iconv_substr')) {
          if(iconv_strlen($fStr, $fCode)>$fLen) {
              return iconv_substr ($fStr, $fStart, $fLen, $fCode) . $show;
          }
          return iconv_substr ($fStr, $fStart, $fLen, $fCode);
      }

      $fCode = strtolower($fCode);
      switch ($fCode) {
          case "utf-8" : 
              preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $fStr, $ar);  
              if(func_num_args() >= 3) {  
                  if (count($ar[0]) > $fLen) {
                      return join("", array_slice($ar[0], $fStart, $fLen)) . $show; 
                  }
                  return join("", array_slice($ar[0], $fStart, $fLen)); 
              } else {  
                  return join("", array_slice($ar[0], $fStart)); 
              } 
              break;
          default:
              $fStart = $fStart * 2;
              $fLen   = $fLen * 2;
              $strlen = strlen($fStr);
              for ( $i = 0; $i < $strlen; $i++ ) {
                  if ( $i >= $fStart && $i < ( $fStart + $fLen ) ) {
                      if ( ord(substr($fStr, $i, 1)) > 129 ) $tmpstr .= substr($fStr, $i, 2);
                      else $tmpstr .= substr($fStr, $i, 1);
                  }
                  if ( ord(substr($fStr, $i, 1)) > 129 ) $i++;
              }
              if ( strlen($tmpstr) < $strlen ) $tmpstr .= $show;
              return $tmpstr;
      }
}

//字符编码安全转换
function safeEncoding($string,$outEncoding ='UTF-8')    
{
	$encoding = "UTF-8";
	for($i=0;$i<strlen($string);$i++)
	{
		if(ord($string{$i})<128)
		continue;

		if((ord($string{$i})&224)==224)
		{
			//第一个字节判断通过
			$char = $string{++$i};
			if((ord($char)&128)==128)
			{
				//第二个字节判断通过
				$char = $string{++$i};
				if((ord($char)&128)==128)
				{
					$encoding = "UTF-8";
					break;
				}
			}
		}
		if((ord($string{$i})&192)==192)
		{
			//第一个字节判断通过
			$char = $string{++$i};
			if((ord($char)&128)==128)
			{
				// 第二个字节判断通过
				$encoding = "GB2312";
				break;
			}
		}
	}

	if(strtoupper($encoding) == strtoupper($outEncoding))
	return $string;
	else
	return iconv($encoding,$outEncoding,$string);
}

//生成随机密码字符串
function generate_password( $length = 8 ) {
    // 密码字符集，可任意添加你需要的字符
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $password = '';
    for ( $i = 0; $i < $length; $i++ )
    {
        // 这里提供两种字符获取方式
        // 第一种是使用 substr 截取$chars中的任意一位字符；
        // 第二种是取字符数组 $chars 的任意元素
        // $password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        $password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
    }
    return $password;
}

//获取图片文件后缀名
function get_imgext($filename = "")
{
	if($filename == "") return false;
	preg_match('|\.(\w+)$|', $filename, $ext);
	$ext = strtolower($ext[1]);
	return $ext;
}

//上传处理
function ciupload($filename)
{
	global $CI;
	$config['upload_path'] = './data/upload_pic';
	$config['allowed_types'] = 'gif|jpg|png';
	$config['file_name'] = strtotime(date('Y-m-d H:i:s')).mt_rand(1,1000);//加上随机数
	$config['max_size'] = 1024*5;
	$config['max_width']  = '0';
	$config['max_height']  = '0';
	$CI->load->library('upload', $config);
	$CI->upload->initialize($config);//初始化上传类
	$pic = "";
	if ($CI->upload->do_upload($filename)) {
		$updata = $CI->upload->data();
		$pic = $updata["file_name"];
	} 
	return $pic;
}

//获取后台路径
function rnadminpath()
{
	global $CI;
	return $CI->config->item('admin_path');
}

/* End of file */